package com.zxy.study.ui.widget;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.Html;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.content.res.ResourcesCompat;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.zxy.study.R;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : Shonn.Zhang
 * @email : shonn.zhang@mart.blue
 * @time : 2020/9/15 11:12
 * @desc :
 */
public class AutoVerticalScrollTextView2 extends FrameLayout {

    private static final int DURATION = 3000;

    private int mScrollTextSize;
    private int mScrollTextColor;

    private ViewPager2 mViewPager2;

    private List<IScrollText> mScrollTextList = new ArrayList<>();

    private onScrollTextListener mOnScrollTextListener;
    private ValueAnimator mScrollAnimator;

    //判断当View可见时，是否自动滚动
    private boolean isAutoScroll;
    private boolean isAttachToWindow;

    private Handler mHandler = new Handler(Looper.getMainLooper());

    /**
     * 用于标识是否需要再View可见时重新开始滚动
     */
    private boolean needReStart;

    public AutoVerticalScrollTextView2(Context context) {
        this(context, null);
    }

    public AutoVerticalScrollTextView2(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AutoVerticalScrollTextView2(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context.obtainStyledAttributes(attrs, R.styleable.AutoVerticalScrollTextView2));
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public AutoVerticalScrollTextView2(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context.obtainStyledAttributes(attrs, R.styleable.AutoVerticalScrollTextView2, defStyleAttr, defStyleRes));
    }

    private void init(TypedArray ta) {
        mScrollTextSize = ta.getDimensionPixelSize(R.styleable.AutoVerticalScrollTextView2_scroll_text_size2, 36);
        mScrollTextColor = ta.getColor(R.styleable.AutoVerticalScrollTextView2_scroll_text_color2, 0xFF5A5E66);
        ta.recycle();

        mViewPager2 = new ViewPager2(getContext());
        mViewPager2.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
        mViewPager2.setOverScrollMode(OVER_SCROLL_NEVER);
        mViewPager2.setVerticalScrollBarEnabled(false);
        mViewPager2.setUserInputEnabled(false);
        mViewPager2.setAdapter(new TextAdapter());

        TextPaint paint = new TextPaint();
        paint.setTextSize(mScrollTextSize);
        paint.measureText("蓝贝");

        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (paint.descent() - paint.ascent() + 15));
        addView(mViewPager2, params);
    }

    public AutoVerticalScrollTextView2 setScrollTextList(List<? extends IScrollText> scrollTextList) {
        if (scrollTextList != null && scrollTextList.size() > 0) {
            mScrollTextList.clear();
            mScrollTextList.addAll(scrollTextList);
        }
        return this;
    }

    public void setOnScrollTextListener(onScrollTextListener mOnScrollTextListener) {
        this.mOnScrollTextListener = mOnScrollTextListener;
    }

    /**
     * 保存前一个animatedValue
     */
    private int mPreviousValue;
    private Runnable mScrollTask = this::showNext;

    /**
     * 切换到下一页
     */
    private void showNext() {
        mPreviousValue = 0;
        mScrollAnimator = ValueAnimator.ofInt(0, mViewPager2.getHeight());
        mScrollAnimator.addUpdateListener(animation -> {
            int currentValue = (int) animation.getAnimatedValue();
            float currentPxToDrag = (float) (currentValue - mPreviousValue);
            mViewPager2.fakeDragBy(-currentPxToDrag);
            mPreviousValue = currentValue;
        });
        mScrollAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                mViewPager2.beginFakeDrag();
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mViewPager2.endFakeDrag();
                if (mOnScrollTextListener != null) {
                    mOnScrollTextListener.onTextShow(mViewPager2.getCurrentItem() % mScrollTextList.size());
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });
        mScrollAnimator.setInterpolator(new AccelerateInterpolator());
        mScrollAnimator.setDuration(1200);
        mScrollAnimator.start();

        mHandler.postDelayed(mScrollTask, DURATION);
    }

    /**
     * 开始滚动播放
     */
    public void start() {
        stop();
        if (mScrollTextList.size() > 0) {
            isAutoScroll = true;
            if (isAttachToWindow && getVisibility() == VISIBLE) {
                mHandler.postDelayed(mScrollTask, DURATION);
            }
            if (mOnScrollTextListener != null) {
                mOnScrollTextListener.onTextShow(mViewPager2.getCurrentItem() % mScrollTextList.size());
            }
        }
    }

    /**
     * 暂停
     */
    private void pause() {
        if (mScrollAnimator != null && mScrollAnimator.isStarted()) {
            mScrollAnimator.cancel();
        }
        mHandler.removeCallbacks(mScrollTask);
    }

    /**
     * 停止滚动播放
     */
    public void stop() {
        pause();
        isAutoScroll = false;
    }

    /**
     * 点击事件
     *
     * @param pos
     */
    private void onTextClick(int pos) {
        if (mOnScrollTextListener != null) {
            int index = pos % mScrollTextList.size();
            IScrollText scrollText = mScrollTextList.get(index);
            mOnScrollTextListener.onTextClick(scrollText.getClickUrl(), scrollText.getId());
        }
    }

    @Override
    protected void onVisibilityChanged(@NonNull View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);

        if (visibility != VISIBLE) {
            pause();
        } else if (getVisibility() == VISIBLE && isAutoScroll) {
            start();
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        isAttachToWindow = true;
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        isAttachToWindow = false;
        pause();
    }

    /**
     * 滚动数据适配器
     */
    private class TextAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            TextView textView = new TextView(getContext());
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mScrollTextSize);
            textView.setTextColor(mScrollTextColor);
            textView.setGravity(Gravity.CENTER_VERTICAL);
            textView.setEllipsize(TextUtils.TruncateAt.END);
            textView.setLines(2);
            textView.setMaxLines(2);
            textView.setTypeface(ResourcesCompat.getFont(getContext(), R.font.roboto_regular));
            textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            RecyclerView.ViewHolder vh = new RecyclerView.ViewHolder(textView) {
            };

            textView.setOnClickListener(v -> {
                int adapterPosition = vh.getAdapterPosition();
                if (adapterPosition != RecyclerView.NO_POSITION) {
                    onTextClick(adapterPosition % mScrollTextList.size());
                }
            });
            return vh;
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            String scrollText = mScrollTextList.get(position % mScrollTextList.size()).getScrollText();
            if (!TextUtils.isEmpty(scrollText)) {
                TextView textView = (TextView) holder.itemView;
                textView.setText(Html.fromHtml(scrollText));
            }
        }

        @Override
        public int getItemCount() {
            return mScrollTextList.size() > 0 ? Integer.MAX_VALUE : 0;
        }
    }

    /**
     * 滚动文本接口
     */
    public interface IScrollText {
        String getId();

        String getScrollText();

        String getClickUrl();
    }

    /**
     * 滚动以及点击监听接口
     */
    public interface onScrollTextListener {
        void onTextClick(String nowClickUrl, String id);

        void onTextShow(int pos);
    }

}
